package c.c.d.s.s.o.a.c.authorization.server.service;

import c.c.d.s.s.o.a.c.authorization.server.domain.entity.User;
import c.c.d.s.s.o.a.c.authorization.server.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Objects;

/**
 * 自定义的 {@link UserDetailsService}
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2020-06-02 16:54
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {

    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        final User user = userMapper.get(username);

        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("用户不存在!");
        }

        return new org.springframework.security.core.userdetails.User(
                user.getName(),
                user.getPassword(),
                Collections.singletonList(new SimpleGrantedAuthority(user.getRole()))
        );
    }

    // ~ autowired
    // -----------------------------------------------------------------------------------------------------------------

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }
}
